package yns.springboot.guide.demo.controller;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import yns.springboot.guide.demo.exception.CommonExceptionInfo;
import yns.springboot.guide.demo.exception.ExceptionCodeEnum;

@RestController
public class TestExceptionController extends BaseController {

	// http://localhost:8080/exception/test
	// http://localhost:8080/exception2/test

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@RequestMapping("/exception/{msg}")
	public String testException(String test, @PathVariable(value = "msg") String msg) throws IOException {
		logger.info(httpServletRequest.getRequestURI());
		logger.info("testException : test=" + test + "  msg=" + msg);

		if ("ex".equals(test)) {
			if ("test".equals(msg)) {
				msg = "This is custom message";
			}

			throw new CommonExceptionInfo(ExceptionCodeEnum.EXCEPTION_TYPE_1, msg);
		} else if ("ex2".equals(test)) {
			throw new IOException();
		}

		return "testException";
	}

	// @ResponseStatus中有两个参数，value属性设置异常的状态码，reaseon是异常的描述
	// 不管该方法是不是发生了异常，将@ResponseStatus注解加在目标方法上，一定会抛出异常。但是如果没有发生异常的话方法会正常执行完毕。
	@ResponseStatus(value = HttpStatus.FORBIDDEN, reason = "不允许访问")
	@RequestMapping("/exception2/{msg}")
	public String testException2(String test, @PathVariable(value = "msg") String msg) {
		logger.info(httpServletRequest.getRequestURI());
		logger.info("testException2 : test=" + test + "  msg=" + msg);

		return "testException2";
	}
}
